<template>
    <div class="home-container">
        <div class="header">
            <div class="header-content">
                <div class="header-title">幻界之旅</div>
                <div class="header-desc">
                    支持角色对话过程中实现人设还原、主动话题引导、剧情推进等能力，请搜索或选择感兴趣的角色进行对话吧！
                </div>
            </div>
        </div>

        <!-- 搜索框 -->
        <div class="search-container">
            <div class="search-input-wrapper">
                <input
                        type="text"
                        v-model="searchKeyword"
                        placeholder="搜索不同的角色..."
                        class="search-input"
                        @keyup.enter="handleSearch"
                />
                <button class="search-btn" @click="handleSearch">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
                         stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="11" cy="11" r="8"></circle>
                        <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                    </svg>
                </button>
            </div>
        </div>

        <div class="section-title">精选应用</div>

        <div class="card-grid">
            <!-- 确保正确绑定点击事件和图片 -->
            <div class="card" v-for="character in displayedCharacters" :key="character.roleKey"
                 @click="goToChat(character)">
                <img
                        class="card-img"
                        :src="character.imageUrl"
                        :alt="character.characterName"
                        @error="handleImageError($event, character)"
                >
                <div class="card-info">
                    <div class="card-title">{{ character.characterName }}</div>
                    <div class="card-desc">{{ character.description }}</div>
                </div>
            </div>
            <!-- 搜索无结果提示 -->
            <div v-if="searchKeyword && displayedCharacters.length === 0" class="no-results">
                <div class="no-results-text">未找到匹配的角色</div>
                <div class="no-results-desc">请尝试使用其他关键词搜索</div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue';
import {useRouter} from 'vue-router';
import {getCharacters, searchCharacters} from '@/services/characterService';

const router = useRouter();
const searchKeyword = ref('');
// 初始化为空数组，完全依赖后端数据
const allCharacters = ref([]);

// 计算属性：根据搜索关键词显示对应的角色
const displayedCharacters = computed(() => {
    if (!searchKeyword.value.trim()) {
        return allCharacters.value;
    }

    return allCharacters.value.filter(char =>
        char.characterName?.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        char.description?.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
});

// 页面加载时获取角色列表
onMounted(() => {
    loadCharacters();
});

// 加载角色列表 - 直接使用后端返回的imageUrl
const loadCharacters = async () => {
    try {
        const response = await getCharacters();
        if (response.code === 1 && response.data) {
            // 直接使用后端返回的数据，不再进行额外处理
            allCharacters.value = response.data;
        }
    } catch (error) {
        console.error('获取角色列表失败:', error);
    }
};

// 搜索功能 - 直接使用后端返回的imageUrl
const handleSearch = async () => {
    const keyword = searchKeyword.value.trim();

    if (!keyword) {
        // 如果搜索关键词为空，显示所有角色
        await loadCharacters();
        return;
    }

    try {
        // 调用后端搜索接口
        const response = await searchCharacters(keyword);
        if (response.code === 1) {
            // 直接使用后端返回的搜索结果
            allCharacters.value = response.data || [];
        }
    } catch (error) {
        console.error('搜索角色失败:', error);
    }
};

const goToChat = (character) => {
    // 确保传递的是角色的roleKey
    const roleKey = typeof character === 'string' ? character : character.roleKey;
    router.push({name: 'chat', params: {character: roleKey}});
};
</script>

<style scoped>
.home-container {
    width: 100%;
    padding: 20px 0;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e5e5e5;
}

.header-content {
    flex: 1;
}

.header-title {
    font-size: 2.5rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 12px;
}

.header-desc {
    color: #666;
    font-size: 1.1rem;
    line-height: 1.6;
    max-width: 1600px;
}

/* 搜索框样式 */
.search-container {
    margin-bottom: 30px;
    display: flex;
    justify-content: center;
}

.search-input-wrapper {
    position: relative;
    width: 100%;
    max-width: 600px;
}

.search-input {
    width: 100%;
    padding: 12px 50px 12px 20px;
    border: 1px solid #ddd;
    border-radius: 24px;
    font-size: 1rem;
    outline: none;
    transition: border-color 0.3s ease;
}

.search-input:focus {
    border-color: #6c63ff;
    box-shadow: 0 0 0 2px rgba(108, 99, 255, 0.1);
}

.search-btn {
    position: absolute;
    right: 4px;
    top: 50%;
    transform: translateY(-50%);
    background: #6c63ff;
    color: white;
    border: none;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.search-btn:hover {
    background: #554eea;
    transform: translateY(-50%) scale(1.05);
}

.section-title {
    font-size: 1.5rem;
    font-weight: 700;
    color: #333;
    margin-bottom: 24px;
    margin-top: 40px;
}

.card-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 32px;
}

.card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    transition: all 0.3s ease;
    cursor: pointer;
    position: relative;
    border: 1px solid #f0f0f0;
}

.card:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 32px rgba(108, 99, 255, 0.18);
}

.card-img {
    width: 100%;
    height: 520px;
    object-fit: cover;
    display: block;
    transition: transform 0.5s ease;
}

.card:hover .card-img {
    transform: scale(1.03);
}

.card-info {
    padding: 20px 24px 16px;
    background: linear-gradient(to top, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.8));
}

.card-title {
    font-size: 1.2rem;
    font-weight: 700;
    color: #333;
    margin-bottom: 8px;
}

.card-desc {
    color: #666;
    font-size: 1rem;
    line-height: 1.5;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 无搜索结果样式 */
.no-results {
    grid-column: 1 / -1;
    text-align: center;
    padding: 60px 20px;
    color: #999;
}

.no-results-text {
    font-size: 1.2rem;
    font-weight: 500;
    margin-bottom: 8px;
}

.no-results-desc {
    font-size: 1rem;
    color: #bbb;
}

/* 响应式设计 */
@media (max-width: 1400px) {
    .card-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 28px;
    }

    .header-title {
        font-size: 2.2rem;
    }
}

@media (max-width: 900px) {
    .header {
        flex-direction: column;
        align-items: flex-start;
        gap: 20px;
    }

    .card-grid {
        grid-template-columns: 1fr;
        gap: 24px;
    }

    .card-img {
        height: 450px;
    }
}

@media (max-width: 600px) {
    .header-title {
        font-size: 1.8rem;
    }

    .header-desc {
        font-size: 1rem;
    }

    .section-title {
        font-size: 1.3rem;
    }

    .card-img {
        height: 380px;
    }
}
</style>